<!--
 * @Description: 目标成本分解查看
 * @Author: wind-lc
 * @version: 1.0
 * @Date: 2024-03-27 14:17:04
 * @LastEditTime: 2024-03-29 11:29:20
 * @FilePath: \cscec-pms-admin\src\views\businessAffairs\businessCostPlanManagement\costPlanManagement\costPlan\components\targetCostDecomposition\index.vue
-->
<template>
  <a-spin :spinning="spinning">
    <a-row :gutter="10" class="page-height wrapper">
      <!-- 树搜索 -->
      <a-col :span="4" class="permission-collapsed" :class="{ 'permission-tree-collapsed': collapsed }">
        <a-card :style="{ border: collapsed ? 'none' : 'border: 1px solid #e8e8e8' }" class="page-height-tree">
          <PermissionTreeOrganization :collapsed.sync="collapsed" parentDisabled @select="handleSelect" :isCostTree="true" :isSecondLevel="true" />
        </a-card>
      </a-col>
      <!-- 树搜索 -->
      <a-col :span="20" class="permission-collapsed page-height-list-wrapper" :style="collapsed ? 'width:calc(100% - 10px)' : ''">
        <a-card :bordered="false" class="page-height-list">
          <a-tabs v-model="key" @change="getTableData">
            <a-tab-pane key="1" tab="三算对比分析表" :disabled="notProjectId">
              <div class="table-wrapper">
                <a-button type="primary" style="margin-bottom: 10px" :disabled="data1.length === 0" @click="handleExpand"> 展示二级科目</a-button>
                <ux-grid
                  ref="table1"
                  :height="height"
                  show-overflow
                  :tree-config="{
                    children: 'children',
                    expandAll: true,
                    iconOpen: 'el-icon-arrow-down',
                    iconClose: 'el-icon-arrow-right'
                  }"
                  row-id="id"
                  border
                  :row-height="40"
                >
                  <ux-table-column
                    v-for="item in columns1"
                    :key="item.dataIndex"
                    :field="item.dataIndex"
                    :title="item.title"
                    :width="item.width"
                    :minWidth="item.minWidth"
                    :fixed="item.fixed"
                    :tree-node="item.dataIndex === 'name'"
                    align="left"
                  >
                    <template v-slot="{ row }">
                      <p :title="row[item.dataIndex]">{{ row[item.dataIndex] | setPlaceholder }}</p>
                    </template>
                  </ux-table-column>
                </ux-grid>
              </div>
            </a-tab-pane>
            <a-tab-pane key="2" tab="目标成本月度分解表" :disabled="notProjectId">
              <a-form-model style="margin:16px 0 0 -30px" ref="ruleForm" :model="form" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }" :rules="{}">
              <custom-form :formList="formList" :form="form" :is-emit="false" :editModel="editModel == 0 ? '' : ''">
                <template #fileList>
                      <template v-if="editModel != 0">
                        <l-table businessCode="FACE12" :uploadArrys.sync="form.fileList"></l-table>
                      </template>
                      <file-link v-else :fileList="form.fileList" style="margin-top: -3px"></file-link>
                    </template>
                </custom-form>
              </a-form-model>
              <div class="table-wrapper">
                <!-- <ux-grid
                  ref="table2"
                  :height="height"
                  show-overflow
                  :tree-config="{
                  children: 'children',
                  expandAll: false,
                  iconOpen: 'el-icon-arrow-down',
                  iconClose: 'el-icon-arrow-right'
                }"
                  row-id="id"
                  border
                  :row-height="40"
                > -->
                <u-table
                  ref="table2"
                  fixed-columns-roll
                  :height="height"
                  show-header-overflow
                  :tree-config="{
                    children: 'children',
                    expandAll: true,
                    iconOpen: 'el-icon-arrow-down',
                    iconClose: 'el-icon-arrow-right'
                  }"
                  row-id="id"
                  :use-virtual="true"
                  border
                  :row-height="40"
                >
                  <u-table-column
                    v-for="item in columns2"
                    :key="item.dataIndex"
                    :prop="item.dataIndex"
                    :label="item.title"
                    :width="item.width"
                    :minWidth="item.minWidth"
                    :fixed="item.fixed"
                    :tree-node="item.dataIndex === 'name'"
                    :field="item.dataIndex"
                    :title="item.title"
                    align="left"
                  >
                    <template v-slot="{ row }">
                      <p v-if="(row.yearMonths || []).findIndex(el => el.key === item.dataIndex) >= 0" @blur="handleUpdate(row, item.dataIndex)">
                        {{ row.detailValues[item.dataIndex] | setPlaceholder }}
                      </p>
                      <p v-else :title="row[item.dataIndex]">{{ row[item.dataIndex]  |  setPlaceholder }}</p>
                    </template>
                  </u-table-column>
                  <!-- </ux-grid> -->
                </u-table>
              </div>
            </a-tab-pane>
          </a-tabs>
        </a-card>
      </a-col>
    </a-row>
  </a-spin>
</template>
<script>
import PermissionTreeOrganization from '@/components/businessComponents/PermissionTreeOrganization'
import { columns1, columns2 } from './model.js'
import { queryPlanOrAdjust } from '@/api/businessAffairs/costAccountInit'
import { placeholder } from '../../../../headquartersDashboard/components/placeholderWay.js'
import { UTable, UTableColumn } from 'umy-ui'
export default {
  name: 'TargetCostDecomposition',
  components: {
    PermissionTreeOrganization,
    UTable,
  },
  data() {
    return {
      // 收缩展开树
      collapsed: false,
      // 三算对比分析表表头
      columns1,
      // 表头
      columns2: this.$clone(columns2),
      // 动态表头
      activeColumns: [],
      // 表格高度
      height: 0,
      // 当前项目id
      projectId: '',
      // 表格key
      key: '1',
      // 表格数据
      data1: [],
      data2: [],
      // 表格加载中
      spinning: false,
      // 表格数据映射
      dataMap: new Map(),
      // 二级科目列表
      secondaryAccount: [],
      form:{},
      editModel:0,
    }
  },
  computed: {
    // 没有项目id
    notProjectId() {
      return (this.projectId ?? '') === ''
    },
    formList() {
      return [
        {
          slot: true,
          keyName: 'fileList',
          label: '佐证材料',
          span: 24
        }
      ]
    }
  },
  filters:{
    setPlaceholder(val){
      return placeholder(val)
    }
  },
  mounted() {
    this.height = document.querySelector('.table-wrapper').offsetHeight - 42
  },
  methods: {
    /**
     * @description: 树选中
     * @param {object} node 节点对象
     * @return {void}
     */
    handleSelect(node) {
      if (node.tageCode === 'PD') {
        this.projectId = node.projectId
        this.getTableData()
      } else {
        this.projectId = ''
        this.data1 = []
        this.data2 = []
        this.dataMap.clear()
        this.secondaryAccount = []
        if (this.key === '1') {
          this.$refs.table1.reloadData([])
        } else {
          this.$refs.table2.reloadData([])
        }
      }
    },
    /**
     * @description: 扁平化树
     * @param {array} tree 树
     * @return {void}
     */
    flattenTree(tree) {
      for (let i = 0; i < tree.length; i++) {
        this.dataMap.set(tree[i].id, tree[i])
        if (tree[i].isShow && tree[i]?.children?.length) {
          this.secondaryAccount.push(tree[i].id)
        }
        if (tree[i]?.children && tree[i].children?.length > 0) {
          this.flattenTree(tree[i].children)
        }
      }
    },
    /**
     * @description: 展开二级科目
     * @return {void}
     */
    handleExpand() {
      this.secondaryAccount.forEach(el => {
        this.$refs.table1.setTreeExpand(this.dataMap.get(el), true)
      })
    },
    /**
     * @description: 获取表格数据
     * @return {void}
     */
    getTableData() {
      this.spinning = true
      if (this.key === '1') {
        queryPlanOrAdjust({
          projectId: this.projectId,
          isHide: false,
          isShow: false
        })
          .then(res => {
            if (res.code === '0') {
              this.businessId = res.data.id
              this.data1 = res.data?.trees || []
              this.secondaryAccount = []
              this.flattenTree(this.data1)
              this.reloadData(this.data1)
            }
          })
          .finally(() => {
            this.spinning = false
          })
      } else {
        queryPlanOrAdjust({
          projectId: this.projectId,
          isHide: true
        })
          .then(res => {
            if (res.code === '0') {
              this.businessId = res.data.id
              this.data2 = res.data?.trees || []
              this.activeColumns = (res.data?.yearMonths || []).map(el => {
                return {
                  title: el.title,
                  width: 150,
                  dataIndex: el.key
                }
              })
              const col = this.$clone(columns2)
              const end = col.pop()
              this.columns2 = [...col, ...this.activeColumns, end]
              console.log(this.columns2,'columns2');
              this.$nextTick(() => {
                this.reloadData(this.data2)
              })
            }
          })
          .finally(() => {
            this.spinning = false
          })
      }
    },
    /**
     * @description: 加载数据
     * @param {array} data 表格数据
     * @return {void}
     */
    reloadData(data) {
      if (this.key === '1') {
        // 获取之前展开数据
        const expandRecords = this.$refs.table1.getTreeExpandRecords()
        // 获取之前滚动高度
        const scroll = this.$refs.table1.tableExample().getScroll()
        // 加载数据
        this.$refs.table1.reloadData(data).then(() => {
          // 数据加载完成出现之后，打开之前的展开行
          expandRecords.forEach(row => {
            this.$refs.table1.setTreeExpand(row, true)
          })
          this.$refs.table1.pagingScrollTopLeft(scroll.scrollTop, scroll.scrollLeft)
        })
      } else {
        // 获取之前展开数据
        console.log( this.$refs.table2,' this.$refs.table2');
        const expandRecords = this.$refs.table2.getTreeExpandRecords()
        // 获取之前滚动高度
        // const scroll = this.$refs.table.tableExample()
      // const scrollLeft = this.$refs.table.tableExample().bodyWrapper.scrollLeft
      //   const scroll = this.$refs.table2.tableExample().getScroll()
        // 加载数据
        this.$refs.table2.reloadData(data).then(() => {
          // 数据加载完成出现之后，打开之前的展开行
          expandRecords.forEach(row => {
            this.$refs.table2.setTreeExpand(row, true)
          })
          // this.$refs.table2.pagingScrollTopLeft(scroll.scrollTop, scroll.scrollLeft)
        })
      }
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';
.wrapper {
  height: 100%;
  @{deep} .ant-card-body,
  .ant-tabs,
  .ant-tabs-tabpane,
  .ant-spin-nested-loading {
    height: 100%;
  }
  .ant-tabs {
    @{deep} .ant-tabs-content {
      height: calc(100% - 54px);
    }
  }
  .ant-spin-nested-loading {
    @{deep} .ant-spin-container {
      height: 100%;
    }
  }
}
.table-wrapper {
  height: 100%;
}
@{deep} .table-wrapper .plTableBox {
  .el-table td {
    padding: 5px 0;
  }
  .el-table th {
    padding: 5px 0;
    height: 40px;
  }
}
@{deep} .table-wrapper .el-table td p,
@{deep} .table-wrapper .elx-table td p {
  margin: 0;
  overflow: hidden;
  text-overflow: ellipsis;
  word-break: break-all;
}
@{deep} .table-wrapper .elx-grid .elx-header--row th,
@{deep} .table-wrapper .elx-table .elx-body--column.col--ellipsis,
.elx-table .elx-footer--column.col--ellipsis,
.elx-table .elx-header--column.col--ellipsis,
.elx-table.elx-editable .elx-body--column {
  padding: 0;
  height: 35px;
}
</style>
